<?php
namespace Admin\Controller;
class SlideController extends CommonController {
	 	 
  /*
   * 幻灯 列表
   *
   */   
  public function  index(){
 
	 $slide_arr=M('slide')->order('sort desc')->select();
 
	 $this->slide=$slide_arr;
	 
	 $this->display();

  }
  
  /*
  * 添加+编辑
  *
  */
  public function add(){
	  
		$act=I('act','');
		$id=I('id',0,'intval');

		if($act=='add')
		{
			 
		    $ztype=I('post.ztype',0);
			$slide_title=I('post.slide_title','');
		 
			$pic=I('post.pic','');
			
            $sort=I('post.sort',0);
			
			$url=I('post.url');
			
			!is_empty($ztype,$slide_title,$pic)?$this->error(L('_IS_EMPTY_')):''; 
			
			 if(!empty($id)){
				
				$old_icon_arr=M('slide')->field('pic')->where(array('slid'=>$id))->find();
				
				if($old_icon_arr['pic']!==$pic)
				{
				
					
					!empty($old_icon_arr['pic'])?unlink($old_icon_arr['pic']):'';
					
					$pic=$this->base64_upload($pic,'slide_'); 
					
				}else{
					
					$pic=$old_icon_arr['pic'];
				}
				
				
				
			}else{
				
				
				   $pic=$this->base64_upload($pic,'slide_'); 
				
			}
			
			
			
			
            $slide_arr=array(
			  'slide_title'=>$slide_title,
              'ztype'=>$ztype,
			  'pic'=>$pic,
			  'sort'=>$sort,
			  'url'=>$url,
			); 
			 
			 $lastId=!empty($id)?M('slide')->where(array('slid'=>$id))->save($slide_arr):M('slide')->add($slide_arr);
			 
		    if(!empty($lastId)){
				 
				$this->success(L('_DO_SUCCEED_'),U('Slide/index')); 
				
				exit;
			 }
			 else{
				
               $this->error(L('_DO_FAILED_')); 				
				 
			 }
			 
			 
		}

	    $this->edit=!empty($id)?M('slide')->where(array('slid'=>$id))->find():'';
  
		$this->display(); 
  } 
  
    /*
	 *
	 *  删除
	 */
	 	public function del(){
		$id=I('post.id',0,'intval');
		if(!empty($id)){

		    $icon_arr=M('slide')->field('pic')->where(array('slid'=>$id))->find();
			
			!empty($icon_arr['pic'])?unlink($icon_arr['pic']):'';
		
			$delId=M('slide')->where(array('slid'=>$id))->delete();
			
		}

		!empty($delId)?message(1,L('_DO_SUCCEED_'),U('Slide/index')):message(2,L('_DO_FAILED_')); 
 
	}
    
	
    /*-----------------------------公共函数---------------------------------------*/ 
	 //上传图片
	public  function base64_upload($base64,$type='') {
			 
        $base64_image = str_replace(' ', '+', $base64);//post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
       
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
		
        //匹配成功
			if($result[2] == 'jpeg'){
				
				$image_name = $type.date('YmdHis',time()).'.jpg'; //纯粹是看jpeg不爽才替换的
				
			}else{
				$image_name = $type.date('YmdHis',time()).'.'.$result[2];
			}
			
           $image_file = "./Uploads/{$image_name}";//服务器文件存储路径
        
			if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
				
				return $image_file;
				
			}else{
				 
				return false;
			}
			
        }
		else
		{
			
           return false;
        }
     }
 
}

 